#!/usr/bin/env bash

# Source the script 'common-functions.sh'.
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
ROOT_DIR=$(grep --only-matching "^.*scripts[^/]*" <<<"$SCRIPT_DIR")
source "$ROOT_DIR/common-functions.sh"

_main() {
    local input_files=""
    local output_dir=""

    # Execute initial checks.
    _check_dependencies "command=iconv; package=libc-bin | command=perl; package=perl-base"
    _display_wait_box "2"
    input_files=$(_get_files "par_type=file; par_recursive=true; par_select_mime='text/|application/json'; par_skip_extension=bak")

    # Execute the function '_main_task' for each file in parallel.
    _run_task_parallel "$input_files" "$output_dir"
    _display_result_box ""
}

_main_task() {
    local input_file=$1
    local output_dir=$2
    local output_file=""
    local std_output=""
    local temp_file1=""
    local temp_file2=""

    # Work on a temporary file.
    temp_file1=$(_get_temp_file)
    temp_file2=$(_get_temp_file)

    # Run the process (part 1) 'convert encoding to utf-8'.
    std_output=$(iconv -f "$(_get_file_encoding "$input_file")" "$input_file" -t utf-8 -o "$temp_file1")
    _check_output "$?" "$std_output" "$input_file" "" || return 1

    # Run the process (part 2) 'convert line breaks to Unix'.
    std_output=$(perl -pe "s/\r\n|\n|\r/\n/g" "$temp_file1" >"$temp_file2")
    _check_output "$?" "$std_output" "$input_file" "" || return 1

    # Run the process (part 3) 'remove trailing spaces'.
    sed -i "s|[ \t]*\(\r*\)$|\1|" "$temp_file2"

    # Run the process (part 4) 'remove the empty line in EOF'.
    printf "\n" >>"$temp_file2"
    sed -i ':Loop;N;$!bLoop;s|\n*$||g' "$temp_file2"

    # Move the temporary file to the output.
    output_file=$input_file
    _move_temp_file_to_output "$input_file" "$temp_file2" "$output_file"

    # Remove the temporary files on each iteration (if not removed before).
    rm -f -- "$temp_file1"
    rm -f -- "$temp_file2"
}

_main "$@"
